var L = require('../../../components/zhgeo/leafletwx')
import {
    createMap
} from '../../../components/zhgeo/base.map'
const app = getApp() //app.globalData

let Lmap, mapType, tif, markerGroup, markers = [],
    timeInterval, timeListIndex = 0


Page({

    /**
     * 页面的初始数据
     */
    data: {
        timeIndex: null,
        startdate: '请选择开始日期',
        enddate: '请选择结束日期',
        second: 1.25,
        percent: 0,
        isPlay: false,
        WHSite: null,
        dynamicHours: [],
        dodynamic: false,
    },
    //获取时间间隔
    getInervalHour(startDate, endDate) {
        var ms = endDate.getTime() - startDate.getTime();
        if (ms < 0) return 0;
        return Math.floor(ms / 1000 / 60 / 60);
    },


    // 播放动态变化
    changePlay(e) {
        let boolean = e.currentTarget.dataset.item
        this.setData({
            isPlay: boolean
        })
        if (boolean) {
            this.startChange()
        } else {
            this.suspendChange()
        }
    },
    // 开始动态变化
    startChange() {
        let startDate = new Date(this.data.startdate);
        let endDate = new Date(this.data.enddate);
        let hours = this.getInervalHour(startDate, endDate);
        if (!this.data.dodynamic) {
            this.setData({
                dodynamic: true
            })
            timeListIndex = 0
            let myDate = new Date();
            let curVal = myDate.valueOf();
            let list = []
            for (var i = hours; i > 0; i--) {
                var curdate = new Date();
                curdate.setTime(curVal - i * 60 * 60 * 1000);
                list.push((new Date(curdate)).Format("yyyy-MM-dd hh:00:00"))
            }
            this.setData({
                dynamicHours: list,
            })
            timeInterval = setInterval(() => {
                //需要同步每帧显示
                if (timeListIndex < this.data.dynamicHours.length) {
                    // if (tif != null) {
                    //     tif.remove();
                    // }
                    this.gethourData();
                    timeListIndex++
                    this.progress()
                } else {
                    this.endChange()
                }
            }, this.data.second * 1000);
            //触发第一次
            this.gethourData();
            timeListIndex++
            this.progress()
        }else{
            timeInterval = setInterval(() => {
                //需要同步每帧显示
                if (timeListIndex < this.data.dynamicHours.length) {
                    // if (tif != null) {
                    //     tif.remove();
                    // }
                    this.gethourData();
                    timeListIndex++
                    this.progress()
                } else {
                    this.endChange()
                }
            }, this.data.second * 1000);
        }
    },

    // 进度条
    progress(){
        let percent = this.data.percent
        let step = 100/this.data.dynamicHours.length
        percent = percent + step
        this.setData({
            percent:percent
        })
    },

    //获取与站点关联的符号
    _getsitemarker(UniqueCode) {
        for (var i = 0; i < this.data.WHSite.length; i++) {
            if (this.data.WHSite[i].uniquecode == UniqueCode) {
                return markers[i];
            }
        }
        return null;
    },
    // 获取每小时站点数据
    gethourData() {
        markers = []
        let type = "wuhan"
        // let imageBounds = [[32.3, 112], [28.4, 116.7]]
        // let imgurl = "/ai-sensing-back-service/api/img/hourimg"
        // let siteUrl = "/ai-sensing-back-service/api/publishData/hourdata"
        let siteUrl = "/ai-sensing-back-service/api/publishData/getStationData"
        markerGroup.remove()
        app.globalData.http.get(siteUrl, {
            area: 'wuhanCC',
            type: 'air',
            time:this.data.dynamicHours[timeListIndex]
        }).then(res => {
            let msg = res.data.list
            msg.map(e => {
                let myIcon = L.marker([e.lat, e.lng], {
                    src: this._getIconColor(e.aqtype),
                    width: 25,
                    height: 25,
                    showInCenter: false,
                })
                markers.push(myIcon)
            })
            markerGroup = L.layerGroup(markers).addTo(Lmap);
        })
    },
    // 结束动态变化
    endChange() {
        this.setData({
            dodynamic: false,
            percent: 0,
            isPlay: false,
        })
        clearInterval(timeInterval);
    },
    // 暂停动态变化
    suspendChange() {
        clearInterval(timeInterval);
    },
    //根据污染等级获取站点图标颜色
    _getIconColor(AQType) {
        switch (AQType) {
            case '优':
                return "https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/analysis/l0.png";
            case '良':
                return "https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/analysis/l1.png";
            case '轻度污染':
                return "https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/analysis/l2.png";
            case '中度污染':
                return "https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/analysis/l3.png";
            case '重度污染':
                return "https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/analysis/l4.png";
            case '严重污染':
                return "https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/analysis/l5.png";
            default:
                return "https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/analysis/nomsg.png";
        }
    },
    // 获取站点
    getStation() {
        // app.globalData.http.get('/ai-sensing-back-service/api/station').then(res => {
        app.globalData.http.get('/ai-sensing-back-service/api/publishData/lastdata').then(res => {
            this.setData({
                WHSite: res.data.items
            })
            this.data.WHSite.map(e => {
                let myIcon = L.marker([e.lat, e.lng], {
                    src: this._getIconColor(e.aqtype),
                    width: 25,
                    height: 25,
                    showInCenter: false,
                })
                markers.push(myIcon)
            })
            // app.globalData.http.get('/ai-sensing-back-service/api/publishData/lastdata').then(res => {
            //     let msg = res.data.items
            //     msg.map(e => {
            //         let marker = this._getsitemarker(e.uniquecode)
            //         if (marker) {
            //             console.log(marker,this._getIconColor(e.aqtype),e.aqtype)
            //             var icon = L.icon({
            //                 iconUrl: '111',
            //                 iconSize: [25, 25]
            //             });
            //             marker.setIcon(icon);
            //             marker.airdata = e;
            //         }
            //     })
            // })
            markerGroup = L.layerGroup(markers).addTo(Lmap);
        })
    },
    // 初始化地图
    setMap() {
        let that = this
        const container = this.selectComponent('#leafletwx')
        let min_zoom = 2
        let max_zoom = 18
        createMap(container, {
            minZoom: min_zoom,
            maxZoom: max_zoom,
        }, function (map) {
            mapType = L.tileLayer('http://webrd03.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}')
            mapType.addTo(map)
            // wx.request({
            //   url: 'https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/json/1%2B8.geojson',
            //   success (res) {
            //     var gj = L.geoJSON(res.data,
            //       {
            //         style: function(feature) {
            //           return {
            //           color: "#3388ff",
            //           fill: true,
            //           fillOpacity: 0.1,
            //           weight: 1,
            //           };
            //         }
            //       }
            //     ).addTo(map)
            //   },
            //   fail (err) {
            //     console.log(err)
            //   }
            // })
            map.setView([29.5, 114.332314], 7)
            Lmap = map
            that.addWms()
        });
    },
    // 加载wms
    addWms() {
        if (!tif) {
            tif = L.tileLayer.wms('http://ai-ecloud.whu.edu.cn/geoserver/PM25WuhanCC/wms?', {
                layers: '20230801080000_reconstruction_clip.tif',
                format: 'image/png',
                transparent: true,
                styles: 'PM25_50'
            })
        }
        tif.addTo(Lmap);

    },
    // 时段选择
    changeTimeIndex(e) {
        let index = e.currentTarget.dataset.item
        this.endChange()
        this.setData({
            timeIndex: index,
            isPlay: false,
            percent: 0
        })
        let a = 1;
        if (index == 1) {
            a = 2;
        } else if (index == 2) {
            a = 14;
        }
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * a);
        this.setData({
            startdate: start.getFullYear() + '-' + (start.getMonth() + 1) + '-' + start.getDate(),
            enddate: start.getFullYear() + '-' + (end.getMonth() + 1) + '-' + end.getDate()
        })
    },
    // 开始日期选择
    bindDateChange(e) {
        this.endChange()
        this.setData({
            startdate: e.detail.value,
        })
    },
    // 结束日期选择
    bindDateChange2(e) {
        this.endChange()
        this.setData({
            enddate: e.detail.value,
        })
    },
    // 清空日期选择
    clearTime(e) {
        this.setData({
            startdate: '请选择开始日期',
            enddate: '请选择结束日期',
        })
    },

    // 减少间隔
    reduceInterval() {
        let interval = this.data.second
        if (interval > 1) {
            interval -= 0.25
        }
        this.setData({
            second: interval
        })
    },
    // 增加间隔
    addInterval() {
        let interval = this.data.second
        if (interval < 3) {
            interval += 0.25
        }
        this.setData({
            second: interval
        })
    },

    // 格式化时间
    setTimeType() {
        // 对Date的扩展，将 Date 转化为指定格式的String
        // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
        // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
        // 例子：
        // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
        // (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  
        Date.prototype.Format = function (fmt) {
          // author: meizz
          var o = {
            "M+": this.getMonth() + 1, // 月份
            "d+": this.getDate(), // 日
            "h+": this.getHours(), // 小时
            "m+": this.getMinutes(), // 分
            "s+": this.getSeconds(), // 秒
            "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
            S: this.getMilliseconds() // 毫秒
          };
          if (/(y+)/.test(fmt))
            fmt = fmt.replace(
              RegExp.$1,
              (this.getFullYear() + "").substr(4 - RegExp.$1.length)
            );
          for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
              fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1
                  ? o[k]
                  : ("00" + o[k]).substr(("" + o[k]).length)
              );
          return fmt;
        };
      },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setTimeType()
        wx.setNavigationBarTitle({
            title: '动态变化',
        })
        this.setMap()
        this.getStation()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})